package domein;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.Observable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Observes messages and updates components of changes.
 *
 * @author Colin Bundervoet
 * @author Jeroen Pattyn
 */
public class MessageObservable extends Observable
{
    private LinkedList<String> messages;

    /**
     * Default constructor for message observable. Initialises the field of
     * messages.
     */
    public MessageObservable() {
        messages = new LinkedList<>();
    }

    /**
     * Appends message to message list. Notifies observers of changes to the
     * list.
     *
     * @param message
     */
    public void addMessage(String message) {
        String time = new SimpleDateFormat().format(new Date());
        message = time + " " + message + "\n";
        messages.addLast(message);
        setChanged();
        notifyObservers(message);
    }

    /*    public String getLastMessage() {
     return messages.getLast();
     }
     */
    /**
     * Writes all files to a specified filename
     *
     * @param filename filename of the file to write messages to.
     */
    public void writeAllMessages(String filename) {
        try {
            PrintWriter out;

            out = new PrintWriter(new FileWriter(new File(filename)));
            while (!messages.isEmpty()) {
                out.println(messages.poll());
            }
            out.close();
        }
        catch (IOException ex) {
            Logger.getLogger(MessageObservable.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
